package org.mig.java.bd.samples;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.mig.java.basics.regulator.regularExpresionator;
import org.mig.java.binding.converter.StringFechaConverter;
import org.mig.java.binding.converter.StringNifConverter;
import org.mig.java.entities.Matricula;

/**
 *
 * @author Hildegard
 */
public class AplicacionBD extends javax.swing.JFrame {

    //Instancio la entidad Matricula
    private Matricula matricula;

    // Sentencia para ejecutar SQL sobre la base de datos
    private Statement stmt = null;

    //Creo las expresiones regulares para comparar los campos.
    private final String EXP_DIR = "(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])";
    private final String EXP_USER = "[a-zA-Z]+";
    private final String EXP_PASS = "[a-zA-Z0-9]+";
    private final String EXP_MAIL = "[a-zA-Z0-9]+@[a-zA-Z]+\\.[a-zA-Z]{3}";
    private final String EXP_NOMBRE = "[a-zA-Z]+";
    private final String EXP_APELLIDOS = "[a-zA-Z]+";
    private final String EXP_NIF = "[0-9]{8}[TRWAGMYFPDXBNJZSQVHLCKE]";
    private final String EXP_EXPEDIENTE = "[0-9]{3}";
    private final String EXP_FECHA = "^(19|20)\\d\\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$";//YYYY-MM-DD
    private final String EXP_TELEFONO = "[0-9]{9}";

    // Nombre de la base de datos
    private final String BD = "agenda";

    // Protocolo del driver JDBC para MySQL
    private final String PROTOCOLO_MySQL = "jdbc:mysql";

    // Servidor
    //private final String SERVIDOR = "192.168.1.35"; <----- Se lo paso mediante el TextField
    private final int PUERTO = 3306;

    // Cadena de conexión de MySQL
    // private final String cadenaMySQL = ""
    //      + PROTOCOLO_MySQL + "://"
    //      + SERVIDOR + ":"
    //      + PUERTO + "/"
    //      + BD;
    //Conexión a la base de datos
    private Connection con = null;

    //Cargo la entidad de comprobacion de errores sintacticos.
    regularExpresionator comprobador = new regularExpresionator();

    /**
     * Creates new form AplicacionBD
     */
    public AplicacionBD() {
        iniciarAnterior();
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        pnlConexion = new javax.swing.JPanel();
        btnConnect = new javax.swing.JButton();
        btnUnconnect = new javax.swing.JButton();
        lblDireccion = new javax.swing.JLabel();
        lblUser = new javax.swing.JLabel();
        lblPassword = new javax.swing.JLabel();
        txfDireccion = new javax.swing.JTextField();
        txfUser = new javax.swing.JTextField();
        txfPassword = new javax.swing.JTextField();
        log = new javax.swing.JTextArea();
        pnlDatos = new javax.swing.JPanel();
        lblExpediente = new javax.swing.JLabel();
        lblNombre = new javax.swing.JLabel();
        lblApellidos = new javax.swing.JLabel();
        lblNif = new javax.swing.JLabel();
        txfExpediente = new javax.swing.JTextField();
        txfNombre = new javax.swing.JTextField();
        txfApellidos = new javax.swing.JTextField();
        lblFechaNacimiento = new javax.swing.JLabel();
        txfNif = new javax.swing.JTextField();
        txfFechaNac = new javax.swing.JTextField();
        lblTelefono = new javax.swing.JLabel();
        lblMail = new javax.swing.JLabel();
        txfMail = new javax.swing.JTextField();
        txfTelefono = new javax.swing.JTextField();
        btnInsertar = new javax.swing.JButton();
        pnlLog = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtLog = new javax.swing.JTextArea();
        pnlComandos = new javax.swing.JPanel();
        btnMostrar = new javax.swing.JButton();
        btnOtro = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Aplicacion BD");
        setResizable(false);

        pnlConexion.setBorder(javax.swing.BorderFactory.createTitledBorder("Conexion"));

        btnConnect.setText("Conectar");
        btnConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConnectActionPerformed(evt);
            }
        });

        btnUnconnect.setText("Desconectar");
        btnUnconnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUnconnectActionPerformed(evt);
            }
        });

        lblDireccion.setText("Direccion BD");

        lblUser.setText("Usuario");

        lblPassword.setText("Contraseña");

        log.setEditable(false);
        log.setBackground(new java.awt.Color(0, 51, 51));
        log.setColumns(20);
        log.setFont(new java.awt.Font("Dialog", 0, 10)); // NOI18N
        log.setForeground(new java.awt.Color(51, 255, 51));
        log.setLineWrap(true);
        log.setRows(5);

        javax.swing.GroupLayout pnlConexionLayout = new javax.swing.GroupLayout(pnlConexion);
        pnlConexion.setLayout(pnlConexionLayout);
        pnlConexionLayout.setHorizontalGroup(
            pnlConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlConexionLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(pnlConexionLayout.createSequentialGroup()
                        .addGroup(pnlConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblUser)
                            .addComponent(lblDireccion)
                            .addComponent(lblPassword))
                        .addGap(18, 18, 18)
                        .addGroup(pnlConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txfDireccion)
                            .addComponent(txfUser)
                            .addComponent(txfPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE)))
                    .addGroup(pnlConexionLayout.createSequentialGroup()
                        .addGap(7, 7, 7)
                        .addComponent(btnConnect)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                        .addComponent(btnUnconnect)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(log)
                .addContainerGap())
        );
        pnlConexionLayout.setVerticalGroup(
            pnlConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlConexionLayout.createSequentialGroup()
                .addGroup(pnlConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlConexionLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(pnlConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDireccion)
                            .addComponent(txfDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(pnlConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblUser)
                            .addComponent(txfUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(pnlConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblPassword)
                            .addComponent(txfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(36, 36, 36)
                        .addGroup(pnlConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnConnect)
                            .addComponent(btnUnconnect)))
                    .addGroup(pnlConexionLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(log, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pnlDatos.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos"));

        lblExpediente.setText("Expediente");

        lblNombre.setText("Nombre");

        lblApellidos.setText("Apellidos");

        lblNif.setText("NIF");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${matricula.expediente}"), txfExpediente, org.jdesktop.beansbinding.BeanProperty.create("text"), "expediente");
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${matricula.nombre}"), txfNombre, org.jdesktop.beansbinding.BeanProperty.create("text"), "nombre");
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${matricula.apellidos}"), txfApellidos, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        lblFechaNacimiento.setText("Fecha Nacimiento");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${matricula.nif}"), txfNif, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setConverter(new StringNifConverter());
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${matricula.fecha}"), txfFechaNac, org.jdesktop.beansbinding.BeanProperty.create("text"), "fecha");
        binding.setConverter(new StringFechaConverter());
        bindingGroup.addBinding(binding);

        lblTelefono.setText("Telefono");

        lblMail.setText("E-Mail");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${matricula.mail}"), txfMail, org.jdesktop.beansbinding.BeanProperty.create("text"), "mail");
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${matricula.telefono}"), txfTelefono, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        btnInsertar.setFont(new java.awt.Font("Dialog", 1, 24)); // NOI18N
        btnInsertar.setText("INSERTAR");
        btnInsertar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInsertarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlDatosLayout = new javax.swing.GroupLayout(pnlDatos);
        pnlDatos.setLayout(pnlDatosLayout);
        pnlDatosLayout.setHorizontalGroup(
            pnlDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDatosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblApellidos)
                    .addComponent(lblExpediente)
                    .addComponent(lblNombre))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(pnlDatosLayout.createSequentialGroup()
                        .addComponent(txfApellidos, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblTelefono))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlDatosLayout.createSequentialGroup()
                        .addComponent(txfNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblFechaNacimiento))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlDatosLayout.createSequentialGroup()
                        .addComponent(txfExpediente, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lblNif)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(pnlDatosLayout.createSequentialGroup()
                        .addComponent(txfNif, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(lblMail)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txfMail, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlDatosLayout.createSequentialGroup()
                        .addGroup(pnlDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txfFechaNac, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txfTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(btnInsertar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pnlDatosLayout.setVerticalGroup(
            pnlDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDatosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblExpediente)
                    .addComponent(txfExpediente, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblNif)
                    .addComponent(txfNif, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblMail)
                    .addComponent(txfMail, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(pnlDatosLayout.createSequentialGroup()
                        .addGroup(pnlDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblNombre)
                            .addComponent(txfNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblFechaNacimiento)
                            .addComponent(txfFechaNac, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(pnlDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblApellidos)
                            .addComponent(txfApellidos, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblTelefono)
                            .addComponent(txfTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(btnInsertar, javax.swing.GroupLayout.DEFAULT_SIZE, 58, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pnlLog.setBorder(javax.swing.BorderFactory.createTitledBorder("Log"));

        txtLog.setEditable(false);
        txtLog.setBackground(new java.awt.Color(0, 0, 0));
        txtLog.setColumns(20);
        txtLog.setFont(new java.awt.Font("Dialog", 0, 10)); // NOI18N
        txtLog.setForeground(new java.awt.Color(102, 255, 102));
        txtLog.setLineWrap(true);
        txtLog.setRows(5);
        jScrollPane1.setViewportView(txtLog);

        javax.swing.GroupLayout pnlLogLayout = new javax.swing.GroupLayout(pnlLog);
        pnlLog.setLayout(pnlLogLayout);
        pnlLogLayout.setHorizontalGroup(
            pnlLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
        );
        pnlLogLayout.setVerticalGroup(
            pnlLogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
        );

        pnlComandos.setBorder(javax.swing.BorderFactory.createTitledBorder("Comandos SQL"));

        btnMostrar.setText("Mostrar");
        btnMostrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnMostrarActionPerformed(evt);
            }
        });

        btnOtro.setText("Otro");

        javax.swing.GroupLayout pnlComandosLayout = new javax.swing.GroupLayout(pnlComandos);
        pnlComandos.setLayout(pnlComandosLayout);
        pnlComandosLayout.setHorizontalGroup(
            pnlComandosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlComandosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlComandosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnMostrar, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)
                    .addComponent(btnOtro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        pnlComandosLayout.setVerticalGroup(
            pnlComandosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlComandosLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnMostrar, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnOtro, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pnlLog, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(pnlDatos, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(pnlConexion, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pnlComandos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(pnlConexion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(pnlDatos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(pnlComandos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlLog, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConnectActionPerformed

        if (comprobarConexionValida()) {
            log.setText("");
            conexionBD();
            pnlDatos.setOpaque(true);
        } else {
            log.append("Algun dato erroneo.");

        }
    }//GEN-LAST:event_btnConnectActionPerformed

    private void btnUnconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUnconnectActionPerformed
        desconectarBD();
    }//GEN-LAST:event_btnUnconnectActionPerformed

    private void btnInsertarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInsertarActionPerformed
        if (comprobarDatosValido() && con != null) {
            try {
                insertarDatos();
            } catch (Exception e) {
                txtLog.append(e.toString() + "\n");
            }

        }
    }//GEN-LAST:event_btnInsertarActionPerformed

    private void btnMostrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMostrarActionPerformed
        if (con != null) {
            txtLog.append("");
            try {
                mostrarDatos();
            } catch (Exception ex) {
                txtLog.append(ex + "\n");
            }
        } else {
            txtLog.append("Conectate a una Base de Datos primero. \n");
        }

    }//GEN-LAST:event_btnMostrarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AplicacionBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AplicacionBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AplicacionBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AplicacionBD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new AplicacionBD().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConnect;
    private javax.swing.JButton btnInsertar;
    private javax.swing.JButton btnMostrar;
    private javax.swing.JButton btnOtro;
    private javax.swing.JButton btnUnconnect;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblApellidos;
    private javax.swing.JLabel lblDireccion;
    private javax.swing.JLabel lblExpediente;
    private javax.swing.JLabel lblFechaNacimiento;
    private javax.swing.JLabel lblMail;
    private javax.swing.JLabel lblNif;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblTelefono;
    private javax.swing.JLabel lblUser;
    private javax.swing.JTextArea log;
    private javax.swing.JPanel pnlComandos;
    private javax.swing.JPanel pnlConexion;
    private javax.swing.JPanel pnlDatos;
    private javax.swing.JPanel pnlLog;
    private javax.swing.JTextField txfApellidos;
    private javax.swing.JTextField txfDireccion;
    private javax.swing.JTextField txfExpediente;
    private javax.swing.JTextField txfFechaNac;
    private javax.swing.JTextField txfMail;
    private javax.swing.JTextField txfNif;
    private javax.swing.JTextField txfNombre;
    private javax.swing.JTextField txfPassword;
    private javax.swing.JTextField txfTelefono;
    private javax.swing.JTextField txfUser;
    private javax.swing.JTextArea txtLog;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    //Getter & Setter Serializado
    public Matricula getMatricula() {
        return matricula;
    }

    public void setMatricula(Matricula matricula) {
        this.matricula = matricula;
    }

    private void iniciarAnterior() {
        matricula = new Matricula();
    }

    private void conexionBD() {
        String direccion = txfDireccion.getText();
        String usuario = txfUser.getText();
        String password = txfPassword.getText();

        try {

            String mensajeConexion = "Conectando con " + BD + "...\n";
            String cadenaMySql = ""
                    + PROTOCOLO_MySQL + "://"
                    + direccion + ":"
                    + PUERTO + "/"
                    + BD;

            //Creo la conexion pasandole el usuario y la contraseña, y la conexion MYSQL de arriba.
            con = DriverManager.getConnection(cadenaMySql, usuario, password);

            log.append(mensajeConexion);

            log.append("\nConectado a " + BD + " como " + usuario);

            // Crear la sentencia para la ejecución de SQL
            stmt = con.createStatement();
        } catch (SQLException e) {
            log.append(e.toString());

        }

    }

    private boolean comprobarConexionValida() {

        boolean comprobarIP = comprobador.comprobarValidez(txfDireccion, EXP_DIR);
        boolean comprobarUser = comprobador.comprobarValidez(txfUser, EXP_USER);
        boolean comprobarPass = comprobador.comprobarValidez(txfPassword, EXP_PASS);

        return comprobarIP && comprobarUser && comprobarPass;
    }

    private boolean comprobarDatosValido() {
        boolean resultado;
        boolean comprobarNombre = comprobador.comprobarValidez(txfNombre, EXP_NOMBRE);
        boolean comprobarApellidos = comprobador.comprobarValidez(txfApellidos, EXP_APELLIDOS);
        boolean comprobarExp = comprobador.comprobarValidez(txfExpediente, EXP_EXPEDIENTE);
        boolean comprobarNif = comprobador.comprobarValidez(txfNif, EXP_NIF);
        boolean comprobarFecha = comprobador.comprobarValidez(txfFechaNac, EXP_FECHA);
        boolean comprobarMail = comprobador.comprobarValidez(txfMail, EXP_MAIL);
        boolean comprobarTelefono = comprobador.comprobarValidez(txfTelefono, EXP_TELEFONO);

        resultado = comprobarApellidos && comprobarExp && comprobarExp && comprobarFecha && comprobarNif && comprobarMail && comprobarNombre && comprobarTelefono;
//
//        System.out.println(comprobarNombre);
//        System.out.println(comprobarApellidos);
//        System.out.println(comprobarExp);
//        System.out.println(comprobarNif);
//        System.out.println(comprobarFecha);
//        System.out.println(comprobarMail);
//        System.out.println(comprobarTelefono);

        return resultado;

    }

    private void insertarDatos() throws Exception {
        System.out.println(matricula.getNombre());
        System.out.println(matricula.getApellidos());
        System.out.println(matricula.getNif().toString());
        System.out.println(txfFechaNac.getText());
        System.out.println(matricula.getTelefono());
        System.out.println(matricula.getMail());

        int exp = matricula.getExpediente();
        String nombre = matricula.getNombre();
        String apellidos = matricula.getApellidos();
        String nif = matricula.getNif().toString();
        String fecha = txfFechaNac.getText();
        int telefono = matricula.getTelefono();
        String mail = matricula.getMail();

        // Sentencia SQL de inserción de datos arbitrarios
        final String SQL = "INSERT INTO Alumno (exp, nombre, apellidos, nif, nac, telefono, email) "
                + "VALUES ("
                + "" + exp + ","
                + "'" + nombre + "', "
                + "'" + apellidos + "',"
                + "'" + nif + "', "
                + "'" + fecha + "', "
                + "" + telefono + ","
                + "'" + mail + "')";

        stmt.addBatch(SQL);

        int[] filas = stmt.executeBatch();

        // Mensaje de valoración final
        txtLog.append(SQL);
        txtLog.append(filas.length + " fila/s insertada/s. \n INSERCION CORRECTA!\n");

    }

    private void mostrarDatos() throws Exception {
        // Preparación del acceso
        final String SQL = "SELECT * FROM Alumno";

        // Lista los datos
        try (ResultSet rs = stmt.executeQuery(SQL)) {
            // Lista los datos
            listarDatos(rs);
        }
    }

    private void listarDatos(ResultSet rs) throws Exception {
        // Mapeado de campos
        int numExp;
        String nombre;
        String apellidos;
        String nif;
        String fechaNac;
        String telefono;
        String email;

        // Cabecera del informe
        txtLog.append("Tabla: Alumnos");
        txtLog.append("----------------------------");

        // Generación del informe - Fila a fila
        while (rs.next()) {
            // Las columnas del ResultSet enpiezan en 1
            // Se pueden referir por su nombre o su posición
            numExp = rs.getInt(1);
            nombre = rs.getString(2);
            apellidos = rs.getString(3);
            nif = rs.getString(4);
            fechaNac = rs.getDate(5).toString();   // Convertir a String
            telefono = rs.getString(6);
            email = rs.getString(7);

            // Genera una linea de texto formateada
            String linea = String.format(
                    "%3d - %-3s - %-20s - %-20s - %10s - %10s - %9s - %s",
                    rs.getRow(), numExp, nombre, apellidos, nif, fechaNac, telefono, email);

            // Muestra la linea
            txtLog.append(linea);
        }
    }

    private void desconectarBD() {

        try {
            con.close();

            System.out.println(con);
        } catch (SQLException e) {
            System.out.println(e);
        }

    }
}
